// oxlint-disable no-unused-vars
/**
 * 可视化编辑器脚本
 * 提供元素选择、悬浮提示、样式管理等功能
 */
(function() {
  let isEditMode = false;
  let hoverTooltip = null;
  let selectedElementsMap = new Map(); // 存储选中元素及其原始样式

  // 创建悬浮提示元素
  const createTooltip = () => {
    if (hoverTooltip) return hoverTooltip;

    hoverTooltip = document.createElement('div');
    hoverTooltip.className = 'visual-editor-tooltip';
    hoverTooltip.style.cssText = `
      position: absolute;
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 8px 12px;
      border-radius: 4px;
      font-size: 12px;
      z-index: 10000;
      pointer-events: none;
      max-width: 300px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      white-space: nowrap;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      line-height: 1.4;
      display: none;
    `;

    document.body.appendChild(hoverTooltip);
    return hoverTooltip;
  };

  // 显示悬浮提示
  const showTooltip = (element, event) => {
    const tooltip = createTooltip();

    // 构建提示内容
    const tagName = element.tagName.toLowerCase();
    const className = element.className ? `.${element.className.split(' ').join('.')}` : '';
    const id = element.id ? `#${element.id}` : '';
    const textContent = element.textContent?.trim().substring(0, 50) || '';

    let content = `<span style="color: #4fc3f7;">${tagName}</span>`;
    if (id) content += `<span style="color: #81c784;">${id}</span>`;
    if (className) content += `<span style="color: #ffb74d;">${className}</span>`;
    if (textContent) content += `<br><span style="color: #e0e0e0;">"${textContent}${textContent.length >= 50 ? '...' : ''}"</span>`;

    tooltip.innerHTML = content;
    tooltip.style.display = 'block';

    // 计算位置
    const rect = element.getBoundingClientRect();
    const tooltipRect = tooltip.getBoundingClientRect();

    let left = event.pageX + 10;
    let top = event.pageY - 10;

    // 防止超出视窗
    if (left + tooltipRect.width > window.innerWidth) {
      left = event.pageX - tooltipRect.width - 10;
    }
    if (top < 0) {
      top = event.pageY + 20;
    }

    tooltip.style.left = left + 'px';
    tooltip.style.top = top + 'px';
  };

  // 隐藏悬浮提示
  const hideTooltip = () => {
    if (hoverTooltip) {
      hoverTooltip.style.display = 'none';
    }
  };

  // 禁用交互元素
  const disableInteractiveElements = () => {
    const interactiveElements = document.querySelectorAll('input, button, select, textarea, a[href], [onclick], [tabindex]');
    interactiveElements.forEach(element => {
      // 保存原始状态
      element.dataset.originalPointerEvents = element.style.pointerEvents || '';
      element.dataset.originalTabIndex = element.tabIndex || '';

      // 禁用交互
      element.style.pointerEvents = 'none';
      element.tabIndex = -1;

      // 添加视觉提示
      element.style.opacity = '0.6';
      element.dataset.visualEditorDisabled = 'true';
    });
  };

  // 恢复交互元素
  const enableInteractiveElements = () => {
    const disabledElements = document.querySelectorAll('[data-visual-editor-disabled="true"]');
    disabledElements.forEach(element => {
      // 恢复原始状态
      element.style.pointerEvents = element.dataset.originalPointerEvents || '';
      element.tabIndex = element.dataset.originalTabIndex ? parseInt(element.dataset.originalTabIndex) : 0;

      // 移除视觉提示
      element.style.opacity = '';

      // 清理数据属性
      delete element.dataset.originalPointerEvents;
      delete element.dataset.originalTabIndex;
      delete element.dataset.visualEditorDisabled;
    });
  };

  // 保存元素原始样式
  const saveOriginalStyles = (element) => {
    if (!selectedElementsMap.has(element)) {
      const originalStyles = {
        outline: element.style.outline || '',
        outlineOffset: element.style.outlineOffset || '',
        background: element.style.background || '',
        backgroundColor: element.style.backgroundColor || '',
        boxShadow: element.style.boxShadow || '',
        position: element.style.position || '',
        zIndex: element.style.zIndex || ''
      };
      selectedElementsMap.set(element, originalStyles);
    }
  };

  // 恢复元素原始样式
  const restoreOriginalStyles = (element) => {
    const originalStyles = selectedElementsMap.get(element);
    if (originalStyles) {
      element.style.outline = originalStyles.outline;
      element.style.outlineOffset = originalStyles.outlineOffset;
      element.style.background = originalStyles.background;
      element.style.backgroundColor = originalStyles.backgroundColor;
      element.style.boxShadow = originalStyles.boxShadow;
      element.style.position = originalStyles.position;
      element.style.zIndex = originalStyles.zIndex;

      // 重置所有可能的修改
      element.style.transform = '';
      element.style.transition = '';

      // 移除类名
      element.classList.remove('visual-editor-hover', 'visual-editor-selected');
      selectedElementsMap.delete(element);
    } else {
      console.warn('⚠️ 未找到元素的原始样式信息');
      // 即使没有保存的样式，也要清理可能的修改
      element.style.outline = '';
      element.style.outlineOffset = '';
      element.style.transform = '';
      element.style.transition = '';
      element.style.zIndex = '';
      element.classList.remove('visual-editor-hover', 'visual-editor-selected');
    }
  };  // 应用悬浮样式
  const applyHoverStyles = (element) => {
    // 使用 outline 而不是 border，避免影响布局
    element.style.outline = '2px dashed #1890ff';
    element.style.outlineOffset = '2px';
    element.classList.add('visual-editor-hover');
  };

  // 移除悬浮样式
  const removeHoverStyles = (element) => {
    if (!element.classList.contains('visual-editor-selected')) {
      element.style.outline = selectedElementsMap.get(element)?.outline || '';
      element.style.outlineOffset = selectedElementsMap.get(element)?.outlineOffset || '';
    }
    element.classList.remove('visual-editor-hover');
  };

  // 应用选中样式
  const applySelectedStyles = (element) => {
    saveOriginalStyles(element);

    // 使用 box-shadow 创建边框效果，避免影响原有样式
    element.style.outline = '2px solid #52c41a';
    element.style.outlineOffset = '2px';
    element.style.boxShadow = (element.style.boxShadow || '') + (element.style.boxShadow ? ', ' : '') + 'inset 0 0 0 1px rgba(82, 196, 26, 0.3)';

    // 添加轻微的背景色，但保持透明度以不覆盖原有背景
    const originalBg = element.style.backgroundColor || getComputedStyle(element).backgroundColor;
    if (originalBg === 'rgba(0, 0, 0, 0)' || originalBg === 'transparent') {
      element.style.backgroundColor = 'rgba(82, 196, 26, 0.05)';
    } else {
      // 如果有背景色，使用 box-shadow 创建叠加效果
      element.style.boxShadow = (element.style.boxShadow || '') + (element.style.boxShadow ? ', ' : '') + 'inset 0 0 0 1000px rgba(82, 196, 26, 0.05)';
    }

    element.classList.add('visual-editor-selected');
  };

  // 消息处理
  const handleMessage = (event) => {
    const { type, payload } = event.data;

    switch (type) {
      case 'ENTER_EDIT_MODE':
        enterEditMode();
        break;
      case 'EXIT_EDIT_MODE':
        exitEditMode();
        break;
      case 'CLEAR_SELECTED_ELEMENTS':
        clearAllSelectedElements();
        break;
      case 'REMOVE_SELECTED_ELEMENT':
        removeSelectedElementById(payload?.elementId);
        break;
      case 'HIGHLIGHT_ELEMENT':
        highlightElementById(payload?.elementId, payload?.isHighlight);
        break;
    }
  };

  // 进入编辑模式
  const enterEditMode = () => {
    isEditMode = true;

    // 设置鼠标为pointer样式
    document.body.style.cursor = 'pointer';
    document.body.style.setProperty('cursor', 'pointer', 'important');

    // 禁用iframe内的交互元素
    disableInteractiveElements();

    document.addEventListener('mouseover', handleMouseOver, true);
    document.addEventListener('mouseout', handleMouseOut, true);
    document.addEventListener('mousemove', handleMouseMove, true);
    document.addEventListener('click', handleClick, true);
  };

  // 退出编辑模式
  const exitEditMode = () => {
    isEditMode = false;

    // 恢复原始鼠标样式
    document.body.style.cursor = '';
    document.body.style.removeProperty('cursor');
    // 移除蓝色主题类
    document.body.classList.remove('visual-editor-blue-cursor');

    // 恢复交互元素
    enableInteractiveElements();

    document.removeEventListener('mouseover', handleMouseOver, true);
    document.removeEventListener('mouseout', handleMouseOut, true);
    document.removeEventListener('mousemove', handleMouseMove, true);
    document.removeEventListener('click', handleClick, true);
    clearAllStyles();
    hideTooltip();

  };

  // 清除所有样式
  const clearAllStyles = () => {
    // 恢复所有选中元素的原始样式
    selectedElementsMap.forEach((originalStyles, element) => {
      restoreOriginalStyles(element);
    });
    selectedElementsMap.clear();

    // 清除所有可能的 hover 样式
    document.querySelectorAll('.visual-editor-hover').forEach(el => {
      el.classList.remove('visual-editor-hover');
      el.style.outline = '';
      el.style.outlineOffset = '';
    });
  };

  // 清除所有选中元素
  const clearAllSelectedElements = () => {
    selectedElementsMap.forEach((originalStyles, element) => {
      restoreOriginalStyles(element);
    });
    selectedElementsMap.clear();
  };

  // 根据ID移除选中元素
  const removeSelectedElementById = (elementId) => {
    const element = document.querySelector(`[data-visual-editor-id="${elementId}"]`);
    if (element) {
      restoreOriginalStyles(element);
      element.removeAttribute('data-visual-editor-id');
    } else {
      console.warn('⚠️ 未找到对应的选中元素:', elementId);
    }
  };

  // 根据ID高亮元素
  const highlightElementById = (elementId, isHighlight) => {
    const element = document.querySelector(`[data-visual-editor-id="${elementId}"]`);
    if (element) {
      if (isHighlight) {
        // 添加高亮效果
        element.style.transform = 'scale(1.02)';
        element.style.transition = 'all 0.2s ease';
        element.style.zIndex = '9999';
        // 增强边框效果
        element.style.outline = '3px solid #ff7a00';
        element.style.outlineOffset = '3px';
      } else {
        // 移除高亮效果
        element.style.transform = '';
        element.style.zIndex = '';
        // 恢复原有边框
        element.style.outline = '2px solid #52c41a';
        element.style.outlineOffset = '2px';
      }
    }
  };

  // 鼠标悬浮处理
  const handleMouseOver = (event) => {
    if (!isEditMode) return;
    const element = event.target;
    if (element === document.body || element === document.documentElement) return;

    if (!element.classList.contains('visual-editor-selected')) {
      element.style.outline = '2px dashed #1890ff';
      element.style.outlineOffset = '2px';
      element.classList.add('visual-editor-hover');
    }
  };

  // 鼠标移出处理
  const handleMouseOut = (event) => {
    if (!isEditMode) return;
    const element = event.target;

    if (!element.classList.contains('visual-editor-selected')) {
      element.style.outline = '';
      element.style.outlineOffset = '';
    }
    element.classList.remove('visual-editor-hover');
    hideTooltip();
  };

  // 鼠标移动处理（用于更新提示位置）
  const handleMouseMove = (event) => {
    if (!isEditMode) return;
    const element = event.target;
    if (element === document.body || element === document.documentElement) return;

    if (element.classList.contains('visual-editor-hover') && !element.classList.contains('visual-editor-selected')) {
      showTooltip(element, event);
    }
  };

  // 点击处理
  const handleClick = (event) => {
    if (!isEditMode) return;

    event.preventDefault();
    event.stopPropagation();

    const element = event.target;
    if (element === document.body || element === document.documentElement) return;

    // 如果已经选中，则取消选中
    if (element.classList.contains('visual-editor-selected')) {
      const elementId = element.getAttribute('data-visual-editor-id');

      restoreOriginalStyles(element);
      element.removeAttribute('data-visual-editor-id');
      hideTooltip();

      // 通知父窗口移除该元素
      if (elementId) {
        window.parent.postMessage({
          type: 'ELEMENT_DESELECTED',
          payload: { elementId }
        }, '*');
      }

      return;
    }

    // 应用选中样式
    applySelectedStyles(element);

    // 生成唯一ID
    const elementId = `element_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    element.setAttribute('data-visual-editor-id', elementId);

    // 获取元素信息
    const elementInfo = {
      id: elementId,
      tagName: element.tagName.toLowerCase(),
      className: element.className || '',
      textContent: element.textContent?.trim().substring(0, 100) || '',
      attributes: Array.from(element.attributes).reduce((acc, attr) => {
        acc[attr.name] = attr.value;
        return acc;
      }, {}),
      xpath: getXPath(element),
      selector: generateSelector(element)
    };

    // 发送选中信息给父窗口
    window.parent.postMessage({
      type: 'ELEMENT_SELECTED',
      payload: elementInfo
    }, '*');

    hideTooltip();
  };

  // 生成 XPath
  const getXPath = (element) => {
    if (element.id) {
      return `//*[@id="${element.id}"]`;
    }

    let path = '';
    while (element && element.nodeType === Node.ELEMENT_NODE) {
      let index = 0;
      let sibling = element.previousSibling;
      while (sibling) {
        if (sibling.nodeType === Node.ELEMENT_NODE && sibling.nodeName === element.nodeName) {
          index++;
        }
        sibling = sibling.previousSibling;
      }

      const tagName = element.nodeName.toLowerCase();
      const pathIndex = index > 0 ? `[${index + 1}]` : '';
      path = `/${tagName}${pathIndex}${path}`;

      element = element.parentNode;
    }

    return path;
  };

  // 生成 CSS 选择器
  const generateSelector = (element) => {
    if (element.id) {
      return `#${element.id}`;
    }

    // 生成更精确的选择器，避免匹配到多个元素
    let selector = element.tagName.toLowerCase();

    // 优先使用原始类名（排除visual-editor相关类名）
    if (element.className) {
      const classes = element.className.trim().split(/\s+/)
        .filter(cls => cls && !cls.startsWith('visual-editor-'));
      if (classes.length > 0) {
        selector += '.' + classes.join('.');
      }
    }

    // 如果选择器仍然不够精确，尝试添加父元素信息
    const parent = element.parentElement;
    if (parent && parent !== document.body && parent !== document.documentElement) {
      // 检查当前选择器是否会匹配到多个元素
      const matchingElements = document.querySelectorAll(selector);
      if (matchingElements.length > 1) {
        // 添加父元素标签名作为上下文
        let parentSelector = parent.tagName.toLowerCase();
        if (parent.id) {
          parentSelector = `#${parent.id}`;
        } else if (parent.className) {
          const parentClasses = parent.className.trim().split(/\s+/)
            .filter(cls => cls && !cls.startsWith('visual-editor-'));
          if (parentClasses.length > 0) {
            parentSelector += '.' + parentClasses.join('.');
          }
        }

        // 检查添加父元素后是否更精确
        const contextSelector = `${parentSelector} > ${selector}`;
        const contextMatches = document.querySelectorAll(contextSelector);
        if (contextMatches.length === 1 && contextMatches[0] === element) {
          selector = contextSelector;
        } else {
          // 如果仍然不精确，使用nth-child
          const siblings = Array.from(parent.children).filter(child =>
            child.tagName.toLowerCase() === element.tagName.toLowerCase()
          );
          if (siblings.length > 1) {
            const index = siblings.indexOf(element) + 1;
            selector = `${parentSelector} > ${element.tagName.toLowerCase()}:nth-child(${index})`;
          }
        }
      }
    }

    // 最后验证选择器的唯一性
    const finalMatches = document.querySelectorAll(selector);
    if (finalMatches.length === 1 && finalMatches[0] === element) {
      return selector;
    }

    // 如果仍然不唯一，使用XPath作为备选方案
    console.warn('生成的CSS选择器不够精确，将使用XPath:', selector);
    return getXPath(element);
  };

  // 监听来自父窗口的消息
  window.addEventListener('message', handleMessage);

  // 通知父窗口脚本已加载
  window.parent.postMessage({ type: 'IFRAME_LOADED' }, '*');

})();
